const axios = require('axios');

const API_BASE_URL = 'http://localhost:4000/api';

// 测试用户资料 API
async function testProfileAPI() {
  try {
    console.log('🚀 开始测试用户资料 API...\n');

    // 1. 用户登录 - 尝试不同的用户名组合
    console.log('1. 尝试用户登录...');
    
    const loginAttempts = [
      { username: 'admin', password: 'admin123' },
      { username: 'admin@example.com', password: 'admin123' },
      { username: 'chengzzh', password: '123456' },
      { username: 'test', password: 'test123' }
    ];

    let token = null;
    let user = null;

    for (const attempt of loginAttempts) {
      try {
        console.log(`   尝试登录: ${attempt.username}`);
        const loginResponse = await axios.post(`${API_BASE_URL}/auth/login`, attempt);
        
        if (loginResponse.data.code === 200) {
          token = loginResponse.data.data.token;
          user = loginResponse.data.data.user;
          console.log('✅ 登录成功');
          console.log(`   用户: ${user.username} (${user.role})`);
          break;
        }
      } catch (error) {
        if (error.response?.status === 401) {
          console.log(`   ❌ 登录失败: ${attempt.username}`);
          continue;
        }
        throw error;
      }
    }

    if (!token) {
      throw new Error('所有登录尝试都失败了，请检查数据库中的用户账户');
    }

    console.log(`   当前资料:`, {
      fullName: user.fullName || '未设置',
      phone: user.phone || '未设置',
      department: user.department || '未设置',
      position: user.position || '未设置',
      bio: user.bio || '未设置',
      location: user.location || '未设置',
      website: user.website || '未设置',
      skills: user.skills || []
    });

    // 设置认证头
    const authHeaders = {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    };

    // 2. 获取当前用户信息
    console.log('\n2. 获取当前用户信息...');
    const meResponse = await axios.get(`${API_BASE_URL}/auth/me`, {
      headers: authHeaders
    });

    if (meResponse.data.code !== 200) {
      throw new Error('获取用户信息失败');
    }

    const currentUser = meResponse.data.data.user;
    console.log('✅ 获取用户信息成功');
    console.log(`   完整资料:`, {
      id: currentUser.id,
      username: currentUser.username,
      email: currentUser.email,
      role: currentUser.role,
      fullName: currentUser.fullName || '未设置',
      phone: currentUser.phone || '未设置',
      department: currentUser.department || '未设置',
      position: currentUser.position || '未设置',
      bio: currentUser.bio || '未设置',
      location: currentUser.location || '未设置',
      website: currentUser.website || '未设置',
      skills: currentUser.skills || []
    });

    // 3. 更新用户资料
    console.log('\n3. 更新用户资料...');
    const updateData = {
      fullName: '程先生',
      phone: '13800138000',
      department: '技术部',
      position: '高级前端工程师',
      bio: '我是一名热爱技术的前端工程师，专注于 React、Vue.js 和 TypeScript 开发。',
      location: '北京市朝阳区',
      website: '', // 测试空字符串
      skills: ['React', 'Vue.js', 'TypeScript', 'Node.js', 'Next.js']
    };

    const updateResponse = await axios.put(`${API_BASE_URL}/auth/profile`, updateData, {
      headers: authHeaders
    });

    if (updateResponse.data.code !== 200) {
      throw new Error('更新用户资料失败');
    }

    const updatedUser = updateResponse.data.data;
    console.log('✅ 更新用户资料成功');
    console.log(`   更新后的资料:`, {
      fullName: updatedUser.fullName,
      phone: updatedUser.phone,
      department: updatedUser.department,
      position: updatedUser.position,
      bio: updatedUser.bio,
      location: updatedUser.location,
      website: updatedUser.website,
      skills: updatedUser.skills
    });

    // 4. 验证更新结果
    console.log('\n4. 验证更新结果...');
    const verifyResponse = await axios.get(`${API_BASE_URL}/auth/me`, {
      headers: authHeaders
    });

    if (verifyResponse.data.code !== 200) {
      throw new Error('验证更新结果失败');
    }

    const verifiedUser = verifyResponse.data.data.user;
    console.log('✅ 验证成功');
    console.log(`   验证结果:`, {
      fullName: verifiedUser.fullName,
      phone: verifiedUser.phone,
      department: verifiedUser.department,
      position: verifiedUser.position,
      bio: verifiedUser.bio,
      location: verifiedUser.location,
      website: verifiedUser.website,
      skills: verifiedUser.skills
    });

    // 5. 测试部分更新
    console.log('\n5. 测试部分更新...');
    const partialUpdateData = {
      bio: '更新后的个人简介：我是一名全栈工程师，专注于现代 Web 技术栈。',
      skills: ['React', 'Vue.js', 'TypeScript', 'Node.js', 'Next.js', 'Python', 'Docker']
    };

    const partialUpdateResponse = await axios.put(`${API_BASE_URL}/auth/profile`, partialUpdateData, {
      headers: authHeaders
    });

    if (partialUpdateResponse.data.code !== 200) {
      throw new Error('部分更新失败');
    }

    const partiallyUpdatedUser = partialUpdateResponse.data.data;
    console.log('✅ 部分更新成功');
    console.log(`   部分更新结果:`, {
      bio: partiallyUpdatedUser.bio,
      skills: partiallyUpdatedUser.skills
    });

    // 6. 测试空值更新
    console.log('\n6. 测试空值更新...');
    const emptyUpdateData = {
      website: '', // 空字符串
      phone: '',   // 空字符串
      bio: ''      // 空字符串
    };

    const emptyUpdateResponse = await axios.put(`${API_BASE_URL}/auth/profile`, emptyUpdateData, {
      headers: authHeaders
    });

    if (emptyUpdateResponse.data.code !== 200) {
      throw new Error('空值更新失败');
    }

    const emptyUpdatedUser = emptyUpdateResponse.data.data;
    console.log('✅ 空值更新成功');
    console.log(`   空值更新结果:`, {
      website: emptyUpdatedUser.website,
      phone: emptyUpdatedUser.phone,
      bio: emptyUpdatedUser.bio
    });

    console.log('\n🎉 所有测试通过！用户资料 API 工作正常。');

  } catch (error) {
    console.error('\n❌ 测试失败:', error.message);
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('响应数据:', error.response.data);
    }
    process.exit(1);
  }
}

// 运行测试
testProfileAPI();
